import { reactive, ref, computed, shallowRef } from 'vue'
import { defineStore } from 'pinia'
import URI from '@/api/URI';
import NetCode from '@/api/NetCode';
import OneUtil from '@/utils/OneUtil';
import Register from '@/register/index';
import ArraysUtil from '@/utils/ArraysUtil';

export const coreStore = defineStore('core', () => {
	const activeKey = reactive({
		tab:"",
		menus:[]
	});
	const menus = reactive([]);
	const pages = [];
	const task = reactive([]);
	
	const init = function() {
		this.$Http.post(URI.CORE.MENUS,{}).then((data)=>{
			if(data.code == NetCode.SUCESS) {
				Register.forEach(item => {
					let m = {};
					m.key = item.key;
					m.label = item.label;
					m.title = item.title;
					m.icon = item.icon;
					m.page = item.page;
					if(OneUtil.ObjectNotNull(item.children) && item.children.length > 0) {
						let arr = [];
						item.children.forEach(i => {
							let subm = {};
							subm.key = i.key;
							subm.label = i.label;
							subm.title = i.title;
							subm.icon = i.icon;
							subm.page = i.page;
							if(item.show) {
								arr.push(subm);
							}
							pages.push(subm);
						});
						m.children = arr;
					}
					if(item.show) {
						menus.push(m);
					}
					pages.push(m);
				})
				//console.log('-> app menus init' + JSON.stringify(menus));
				openPage("0000");
			}
		});
	}
	const setActive = function(key) {
		activeKey.tab = key;
		activeKey.menus = [];
		activeKey.menus.push(key);
	}
	
	const openPage = function(key) {
		let t = ArraysUtil.findByKey(task,key);
		if(OneUtil.ObjectNotNull(t)) {
			setActive(t.key);
		} else {
			let p = ArraysUtil.findByKey(pages,key);
			if(OneUtil.ObjectNotNull(p)) {
				
				task.push(p);
				setActive(p.key);
			}
		}
	}
	
	const closePage = function(key) {
		let index = ArraysUtil.findIndexByKey(task,key);
		ArraysUtil.deleteByIndex(task,index);
		//console.log('-> index' + JSON.stringify(index));
		index = index < task.length ? index:(task.length - 1);
		if(task.length > 0) {
			let next = task[index];
			setActive(next.key);
		}
	}
	
	return {init, menus, activeKey, task, openPage, closePage, setActive}
})
